﻿using System;
using System.Collections.Generic;
using System.Linq;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Mappers;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess
{
    internal class CmsUserInformationForManagementDataCommand : CmsUserInformationForManagementCommand
    {
        public override IQueryable<CmsUserInformation> Execute()
        {
            IEnumerable<CmsUserInformation> result = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsUserInformation>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsUserInformation>;

            if (currentUnitOfWork != null)
            {
                if (CommandParameter.Id > 0)
                {
                    var unit = SqlUtility<CmsUserInformation, int>.ExecuteMultiReader(
                    currentUnitOfWork.Connection,
                    currentUnitOfWork.Transaction,
                    "cms_sp_GetUserForManagement",
                    new
                    {
                        UserId = CommandParameter.Id
                    },
                    new CmsUserInformationAllForManagementDataMapper());

                    if (unit != null)
                    {
                        var list = new List<CmsUserInformation>();
                        list.Add(unit);

                        result = list;
                    }
                }
                else
                {
                    result = SqlUtility<CmsUserInformation, int>.ExecuteReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_GetUsersForManagement",
                        new
                        {
                            CurrentPage = CommandParameter.CurrentPage,
                            PageCapacity = CommandParameter.PageCapacity,
                            SiteId = CommandParameter.SiteId,
                            SiteGroupId = CommandParameter.SiteGroupId,
                            CommandParameter.SortField,
                            CommandParameter.SortDirection
                        },
                        new CmsUserInformationAllForManagementDataMapper());
                }
            }

            return result != null ?
                result.AsQueryable() :
                new List<CmsUserInformation>().AsQueryable();
        }
    }
}
